package logic

import (
	"context"
	"encoding/json"
	"goods/goodsrpc/goodsrpc"
	"goods/goodsrpc/internal/svc"
	"goods/model/cache"
	"goods/model/mysql"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type GoodsListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodsListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodsListLogic {
	return &GoodsListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GoodsListLogic) GoodsList(in *goodsrpc.GoodsListRequest) (*goodsrpc.GoodsListResponse, error) {
	// todo: add your logic here and delete this line

	var Goods []mysql.GoodsData
	result, _ := cache.Rdb.Get(l.ctx, "GoodsList").Result()
	if result == "" {
		mysql.DB.Debug().Model(&mysql.Goods{}).
			Select("goods.*, classes.name as class_name,brands.name as brand_name").
			Joins("left join classes on classes.id = goods.class_id").
			Joins("left join brands on brands.id = goods.brand_id").
			Find(&Goods)

		marshal, _ := json.Marshal(&Goods)
		cache.Rdb.Set(l.ctx, "GoodsList", marshal, time.Hour*1)
	} else {
		json.Unmarshal([]byte(result), &Goods)
	}

	var Good []*goodsrpc.GoodsLiat
	for _, good := range Goods {
		list := goodsrpc.GoodsLiat{
			Name:      good.Name,
			Image:     good.Image,
			Price:     float32(good.Price),
			ClassName: good.ClassName,
			BrandName: good.BrandName,
			GoodsId:   int64(good.ID),
		}
		Good = append(Good, &list)
	}

	return &goodsrpc.GoodsListResponse{
		List: Good,
	}, nil
}
